package com.xiaode.util;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.ThreadPoolKit;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ChatUtil {
    private static final Prop prop;
    private static final Logger logger = LogManager.getLogger("errorLoger");
    private static final Map<Integer,String> userTypeMap = new HashMap<Integer,String>();

    static {
        //初始化prop
        prop = PropKit.use("server.properties");
        userTypeMap.put(1,"A");
        userTypeMap.put(2,"B");
        userTypeMap.put(3,"C");
    }

    /**
     * 添加好友
     */
    public static void addFriends(Integer userId, List<Integer> friendIds) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("userId", userId + "");
        String s = JSONUtil.toJsonStr(friendIds);
        paramMap.put("jsonFriendIds", s);
        final int[] i = {0};
        final String[] response = {""};
        ThreadPoolKit.execute(new Thread(){
        @Override
        public void run () {
            do {
                response[0] = HttpRequest.post(prop.get("chat.ip")+"/imSys/addFriends")
                        .header("serviceId", prop.get("chat.serviceId"))
                        .header("accessKey", prop.get("chat.accessKey"))
                        .header("secretKey", prop.get("chat.secretKey"))
                        .timeout(3000).form(paramMap).execute().body();
            } while (!JSONUtil.parseObj(response[0]).getStr("state").equals("ok") && ++i[0] <= 3);
            if (!"ok".equals(JSONUtil.parseObj(response[0]).getStr("state"))){
                logger.info("请求聊天系统失败,添加好友失败");
            }
        }}
        );
    }

    /**
     * 添加群 (一个用户添加多个群)
     */
    public static void addGroups(Integer userId, List<Integer> friendIds) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("userId", userId + "");
        String s = JSONUtil.toJsonStr(friendIds);
        paramMap.put("jsonGroupIds", s);
        final int[] i = {0};
        final String[] response = {""};
        ThreadPoolKit.execute(new Thread(){
            @Override
            public void run() {
                do {
                    response[0] = HttpRequest.post(prop.get("chat.ip")+"/imSys/addGroups")
                            .header("serviceId", prop.get("chat.serviceId"))
                            .header("accessKey", prop.get("chat.accessKey"))
                            .header("secretKey", prop.get("chat.secretKey"))
                            .timeout(3000).form(paramMap).execute().body();
                } while (!JSONUtil.parseObj(response[0]).getStr("state").equals("ok") && ++i[0] <= 3);
                if (!"ok".equals(JSONUtil.parseObj(response[0]).getStr("state"))){
                    logger.info("请求聊天系统失败,添加群聊失败");
                }
            }
        });
    }

    /**
     * 添加群(一个群添加多个用户)
     */
    public static void addGroupsByGroupId(Integer groupId,List<Integer> jsonUserIds){
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("groupId", groupId+ "");
        String s = JSONUtil.toJsonStr(jsonUserIds);
        paramMap.put("jsonUserIds", s);
        final int[] i = {0};
        final String[] response = {""};
        ThreadPoolKit.execute(new Thread(){
            @Override
            public void run() {
                do {
                    response[0] = HttpRequest.post(prop.get("chat.ip")+"/imSys/addGroupsByGroupId")
                            .header("serviceId", prop.get("chat.serviceId"))
                            .header("accessKey", prop.get("chat.accessKey"))
                            .header("secretKey", prop.get("chat.secretKey"))
                            .timeout(3000).form(paramMap).execute().body();
                } while (!JSONUtil.parseObj(response[0]).getStr("state").equals("ok") && ++i[0] <= 3);
                if (!"ok".equals(JSONUtil.parseObj(response[0]).getStr("state"))){
                    logger.info("请求聊天系统失败,一个群添加多个用户失败");
                }
            }
        });
    }

    /**
     * 添加群(一个群中退出多个用户)
     *
     */
    public static void deleGroupsByGroupId(Integer groupId,List<Integer> jsonUserIds){
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("groupId", groupId+ "");
        String s = JSONUtil.toJsonStr(jsonUserIds);
        paramMap.put("jsonUserIds", s);
        final int[] i = {0};
        final String[] response = {""};
        ThreadPoolKit.execute(new Thread(){
            @Override
            public void run() {
                do {
                    response[0] = HttpRequest.post(prop.get("chat.ip")+"/imSys/deleGroupsByGroupId")
                            .header("serviceId", prop.get("chat.serviceId"))
                            .header("accessKey", prop.get("chat.accessKey"))
                            .header("secretKey", prop.get("chat.secretKey"))
                            .timeout(3000).form(paramMap).execute().body();
                } while (!JSONUtil.parseObj(response[0]).getStr("state").equals("ok") && ++i[0] <= 3);
                if (!"ok".equals(JSONUtil.parseObj(response[0]).getStr("state"))){
                    logger.info("请求聊天系统失败,一个群添加多个用户失败");
                }
            }
        });
    }



    /**
     * 删除好友
     */
    public static void deleFriends(Integer userId, List<Integer> friendIds) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("userId", userId + "");
        String s = JSONUtil.toJsonStr(friendIds);
        paramMap.put("jsonFriendIds", s);
        final int[] i = {0};
        final String[] response = {""};
        ThreadPoolKit.execute(new Thread(){
            @Override
            public void run() {
                do {
                    response[0] = HttpRequest.post(prop.get("chat.ip")+"/imSys/deleFriends")
                            .header("serviceId", prop.get("chat.serviceId"))
                            .header("accessKey", prop.get("chat.accessKey"))
                            .header("secretKey", prop.get("chat.secretKey"))
                            .timeout(3000).form(paramMap).execute().body();
                } while (!JSONUtil.parseObj(response[0]).getStr("state").equals("ok") && ++i[0] <= 3);
                if (!"ok".equals(JSONUtil.parseObj(response[0]).getStr("state"))){
                    logger.info("请求聊天系统失败,删除好友失败");
                }
            }
        });
    }

    /**
     * 删除群
     */
    public static void deleGroups(Integer userId, List<Integer> jsonGroupIds) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("userId", userId + "");
        String s = JSONUtil.toJsonStr(jsonGroupIds);
        paramMap.put("jsonGroupIds", s);
        final int[] i = {0};
        final String[] response = {""};
        ThreadPoolKit.execute(new Thread(){
            @Override
            public void run() {
                do {
                    response[0] = HttpRequest.post(prop.get("chat.ip")+"/imSys/deleGroups")
                            .header("serviceId", prop.get("chat.serviceId"))
                            .header("accessKey", prop.get("chat.accessKey"))
                            .header("secretKey", prop.get("chat.secretKey"))
                            .timeout(3000).form(paramMap).execute().body();
                } while (!JSONUtil.parseObj(response[0]).getStr("state").equals("ok") && ++i[0] <= 3);
                if (!"ok".equals(JSONUtil.parseObj(response[0]).getStr("state"))){
                    logger.info("请求聊天系统失败,删除群组失败");
                }
            }
        });

    }

    /**
     * 群中用户禁言
     */
    public static void estoppelByGroup(Integer groupId, List<Integer> jsonUserIds) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("groupId", groupId + "");
        String s = JSONUtil.toJsonStr(jsonUserIds);
        paramMap.put("jsonUserIds", s);
        final int[] i = {0};
        final String[] response = {""};
        ThreadPoolKit.execute(new Thread(){
            @Override
            public void run() {
                do {
                    response[0] = HttpRequest.post(prop.get("chat.ip")+"/imSys/estoppelByGroup")
                            .header("serviceId", prop.get("chat.serviceId"))
                            .header("accessKey", prop.get("chat.accessKey"))
                            .header("secretKey", prop.get("chat.secretKey"))
                            .timeout(3000).form(paramMap).execute().body();
                } while (!JSONUtil.parseObj(response[0]).getStr("state").equals("ok") && ++i[0] <= 3);
                if (!"ok".equals(JSONUtil.parseObj(response[0]).getStr("state"))){
                    logger.info("请求聊天系统失败,群众用户禁言失败");
                }
            }
        });


    }

    /**
     * 用户禁言
     */
    public static void estoppelByUser(List<Integer> jsonUserIds) {
        HashMap<String, Object> paramMap = new HashMap<>();
        String s = JSONUtil.toJsonStr(jsonUserIds);
        paramMap.put("jsonUserIds", s);
        final int[] i = {0};
        final String[] response = {""};
        ThreadPoolKit.execute(new Thread(){
            @Override
            public void run() {
                do {
                    response[0] = HttpRequest.post(prop.get("chat.ip")+"/imSys/estoppelByUser")
                            .header("serviceId", prop.get("chat.serviceId"))
                            .header("accessKey", prop.get("chat.accessKey"))
                            .header("secretKey", prop.get("chat.secretKey"))
                            .timeout(3000).form(paramMap).execute().body();
                } while (!JSONUtil.parseObj(response[0]).getStr("state").equals("ok") && ++i[0] <= 3);
                if (!"ok".equals(JSONUtil.parseObj(response[0]).getStr("state"))){
                    logger.info("请求聊天系统失败,用户禁言失败");
                }
            }
        });


    }

    /**
     * 获取客户端token
     */
    public static String getClientToken(Integer userId) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("userId", userId + "");
        int i = 0;
        String response = "";
        do {
            response = HttpRequest.post(prop.get("chat.ip")+"/imSys/getClientToken")
                    .header("serviceId", prop.get("chat.serviceId"))
                    .header("accessKey", prop.get("chat.accessKey"))
                    .header("secretKey", prop.get("chat.secretKey"))
                    .form(paramMap).execute().body();
        } while (!JSONUtil.parseObj(response).getStr("state").equals("ok") && ++i <= 3);
        if (!"ok".equals(JSONUtil.parseObj(response).getStr("state"))){
            logger.info("请求聊天系统失败,获取token失败");
        }
        return response;
    }

    /**
     * 群中用户解除禁言
     */
    public static void relieveEstoppelByGroup(Integer groupId, List<Integer> jsonUserIds) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("groupId", groupId + "");
        String s = JSONUtil.toJsonStr(jsonUserIds);
        paramMap.put("jsonUserIds", s);
        final int[] i = {0};
        final String[] response = {""};
        ThreadPoolKit.execute(new Thread(){
            @Override
            public void run() {
                do {
                    response[0] = HttpRequest.post(prop.get("chat.ip")+"/imSys/relieveEstoppelByGroup")
                            .header("serviceId", prop.get("chat.serviceId"))
                            .header("accessKey", prop.get("chat.accessKey"))
                            .header("secretKey", prop.get("chat.secretKey"))
                            .timeout(3000).form(paramMap).execute().body();
                } while (!JSONUtil.parseObj(response[0]).getStr("state").equals("ok") && ++i[0] <= 3);
                if (!"ok".equals(JSONUtil.parseObj(response[0]).getStr("state"))){
                    logger.info("请求聊天系统失败,群众用户解除禁言失败");
                }
            }
        });

    }

    /**
     * 用户解除禁言
     */
    public static void relieveEstoppelByUser(List<Integer> jsonUserIds) {
        HashMap<String, Object> paramMap = new HashMap<>();
        String s = JSONUtil.toJsonStr(jsonUserIds);
        paramMap.put("jsonUserIds", s);
        final int[] i = {0};
        final String[] response = {""};
        ThreadPoolKit.execute(new Thread(){
            @Override
            public void run() {
                do {
                    response[0] = HttpRequest.post(prop.get("chat.ip")+"/imSys/relieveEstoppelByUser")
                            .header("serviceId", prop.get("chat.serviceId"))
                            .header("accessKey", prop.get("chat.accessKey"))
                            .header("secretKey", prop.get("chat.secretKey"))
                            .timeout(3000).form(paramMap).execute().body();
                } while (!JSONUtil.parseObj(response[0]).getStr("state").equals("ok") && ++i[0] <= 3);
                if (!"ok".equals(JSONUtil.parseObj(response[0]).getStr("state"))){
                    logger.info("请求聊天系统失败,用户解除禁言失败");
                }
            }
        });

    }

    /**
     * 解除拉黑
     */
    public static void removeBlock(Integer userId, List<Integer> jsonBlockIds) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("userId", userId + "");
        String s = JSONUtil.toJsonStr(jsonBlockIds);
        paramMap.put("jsonBlockIds", s);
        final int[] i = {0};
        final String[] response = {""};
        ThreadPoolKit.execute(new Thread(){
            @Override
            public void run() {
                do {
                    response[0] = HttpRequest.post(prop.get("chat.ip")+"/imSys/removeBlock")
                            .header("serviceId", prop.get("chat.serviceId"))
                            .header("accessKey", prop.get("chat.accessKey"))
                            .header("secretKey", prop.get("chat.secretKey"))
                            .timeout(3000).form(paramMap).execute().body();
                } while (!JSONUtil.parseObj(response[0]).getStr("state").equals("ok") && ++i[0] <= 3);
                if (!"ok".equals(JSONUtil.parseObj(response[0]).getStr("state"))){
                    logger.info("请求聊天系统失败,解除拉黑失败");
                }
            }
        });

    }

    /**
     * 拉黑
     */
    public static void setBlock(Integer userId, List<Integer> jsonBlockIds) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("userId", userId + "");
        String s = JSONUtil.toJsonStr(jsonBlockIds);
        paramMap.put("jsonBlockIds", s);
        final int[] i = {0};
        final String[] response = {""};
        ThreadPoolKit.execute(new Thread(){
            @Override
            public void run() {
                do {
                    response[0] = HttpRequest.post(prop.get("chat.ip")+"/imSys/setBlock")
                            .header("serviceId", prop.get("chat.serviceId"))
                            .header("accessKey", prop.get("chat.accessKey"))
                            .header("secretKey", prop.get("chat.secretKey"))
                            .timeout(3000).form(paramMap).execute().body();
                } while (!JSONUtil.parseObj(response[0]).getStr("state").equals("ok") && ++i[0] <= 3);
                if (!"ok".equals(JSONUtil.parseObj(response[0]).getStr("state"))){
                    logger.info("请求聊天系统失败,拉黑失败");
                }
            }
        });

    }

    /**
     * 发送通知用户
     */
    public static void sendNotice(String noticeJson, Integer noticeType, List<Integer> jsonUserIds) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("noticeJson", noticeJson);
        String s = JSONUtil.toJsonStr(jsonUserIds);
        paramMap.put("jsonUserIds", s);
        paramMap.put("noticeType", noticeType);
        final int[] i = {0};
        final String[] response = {""};
        ThreadPoolKit.execute(new Thread(){
            @Override
            public void run() {
                do {
                    response[0] = HttpRequest.post(prop.get("chat.ip")+"/imSys/sendNotice")
                            .header("serviceId", prop.get("chat.serviceId"))
                            .header("accessKey", prop.get("chat.accessKey"))
                            .header("secretKey", prop.get("chat.secretKey"))
                            .timeout(3000).form(paramMap).execute().body();
                } while (!JSONUtil.parseObj(response[0]).getStr("state").equals("ok") && ++i[0] <= 3);
                if (!"ok".equals(JSONUtil.parseObj(response[0]).getStr("state"))){
                    logger.info("请求聊天系统失败,发送通知给用户失败");
                }
            }
        });

    }

    /**
     * 发送通知给全体用户
     */
    public static void sendNoticeAll(String noticeJson, Integer noticeType) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("noticeJson", noticeJson);
        paramMap.put("noticeType", noticeType);
        final int[] i = {0};
        final String[] response = {""};
        ThreadPoolKit.execute(new Thread(){
            @Override
            public void run() {
                do {
                    response[0] = HttpRequest.post(prop.get("chat.ip")+"/imSys/sendNoticeAll")
                            .header("serviceId", prop.get("chat.serviceId"))
                            .header("accessKey", prop.get("chat.accessKey"))
                            .header("secretKey", prop.get("chat.secretKey"))
                            .timeout(3000).form(paramMap).execute().body();
                } while (!JSONUtil.parseObj(response[0]).getStr("state").equals("ok") && ++i[0] <= 3);
                if (!"ok".equals(JSONUtil.parseObj(response[0]).getStr("state"))){
                    logger.info("请求聊天系统失败,发送通知给全体用户失败");
                }
            }
        });
    }


    /**
     * 设置群聊需要已读未读
     */
    public static void setGroupReadAbility(Integer groupId, Boolean needRead) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("groupId", groupId + "");
        paramMap.put("needRead", needRead);
        final int[] i = {0};
        final String[] response = {""};
        ThreadPoolKit.execute(new Thread(){
            @Override
            public void run() {
                do {
                    response[0] = HttpRequest.post(prop.get("chat.ip")+"/imSys/setGroupReadAbility")
                            .header("serviceId", prop.get("chat.serviceId"))
                            .header("accessKey", prop.get("chat.accessKey"))
                            .header("secretKey", prop.get("chat.secretKey"))
                            .timeout(3000).form(paramMap).execute().body();
                } while (!JSONUtil.parseObj(response[0]).getStr("state").equals("ok") && ++i[0] <= 3);
                if (!"ok".equals(JSONUtil.parseObj(response[0]).getStr("state"))){
                    logger.info("请求聊天系统失败,发送群聊是否需要已读未读失败");
                }
            }
        });
    }



    /**
     * 生成会话id
     */
    @Deprecated
    public static String generateConversation(Integer userId1,Integer userType1,Integer userId2,Integer userType2){
        String s = userTypeMap.get(userType1);
        String s1 = userTypeMap.get(userType2);
        return userId1 > userId2 ? s + s1 + userId1 + userId2 : s1 + s + userId2 + userId1;
    }
    public static String sessionId(Integer fromUserId, Integer toUserId) {
		if (fromUserId <= toUserId) {
			return fromUserId + "-" + toUserId;
		} else {
			return toUserId + "-" + fromUserId;
		}
	}


}
